// approval/pages/leave_approval/leave_approval.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    impPath: '/components/approval/approval',
    temList: ['approval', 'approvalInfo'],
    picPath: app.globalData.picPath,
    imgApproval: '',
    stautsApproval: true,
    readDataShow: false,
    approval_name: '', // 申请人姓名
    examInfo: {
      approval: false,
      examMemberDetail: '',
      detial: true,
      return: false,
      leaveClass: false,
      noBtn: true
    },
    show: false,
    addLeaveExam: {
      memberId: app.globalData.memberId,
      leaveExamType: '',
      startTime: '',
      endTime: '',
      leaveExamHandover: '',
      leaveExamDetail: '',
      dateTime: '',
      leaveExamStatus: '0',
      note: '',
      examMemberId: '',
      leaveExamType: '',
      approval: false
    },
    leaveTime: '', //请假时间
    dayStart: '', //开始请假时间的选中
    dayEnd: '', //结束请假时间的选中
    datStatus: 0, //天---请假类型选中
    dayTpye: ['上午', '下午'], //天---请假类型
    startTime: '', //开始时间
    endTime: '', //结束时间
    flag: '', //判断是开始还是结束时间
    timeTitle: '', //开始时间结束时间标题
    showTime: false, //开始结束时间
    currentDate: new Date().getTime(), //选择时间
    minDate: new Date().getTime(), //选择时间
    doalig: false, //请假类型弹窗
    listProps: {
      topList: [],
      btmList: [],
      readonlyStatus: false, // 是否只读
    },
    value: '',
    type: '',
    active: 0, //判断选择请假类型的样式
    //请假类型数组
    typeList: [{
        index: 0,
        name: '事假'
      },
      {
        index: 1,
        name: '病假'
      },
      {
        index: 2,
        name: '婚假'
      },
      {
        index: 3,
        name: '产假'
      },
      {
        index: 4,
        name: '陪产假'
      },
      {
        index: 5,
        name: '丧假'
      },
      {
        index: 6,
        name: '其他'
      }
    ],
    date1: '',
    date2: '',
    formatter(type, val) {
      if (type === 'year') {
        return val + '年';
      }
      if (type === 'month') {
        return val + '月';
      }
      if (type === 'day') {
        return val + '日';
      }
      return val;
    },
  },

  // 关闭选择请假类型弹窗
  onTypeClose(e) {
    this.setData({
      doalig: false
    })
  },
  // 组件事件
  change(obj) {
    console.log(obj);
    this.setData({
      listProps: JSON.parse(wx.getStorageSync('listProps'))
    })
    console.log(this.data.listProps);
  },

  // 选择请假类型
  onSelectType(e) {
    console.log(e);
    var val = e.detail.name,
      index = e.detail.index,
      str = 'addLeaveExam.leaveExamType';
    console.log(val);

    this.setData({
      [str]: index,
      type: val,
      doalig: false
    })
  },
  // 显示弹窗
  showHandle(e) {
    console.log(e);
    var flag = e.currentTarget.dataset.flag
    console.log(flag);
    if (flag == 'type') {
      this.setData({
        doalig: true
      })
    } else if (flag == 'timeStart') {
      this.setData({
        showTime: true,
        timeTitle: '开始'
      })
    } else if (flag == 'timeEnd') {
      this.setData({
        showTime: true,
        timeTitle: '结束'
      })
    }
  },

  // 选择日期
  selectTime(e) {
    console.log(e);
    var time = new Date(e.detail)
    console.log(time);

    if (this.data.timeTitle == '开始') {
      var str = 'addLeaveExam.startTime',
        startTime = (this.formatDate(time) + ' ' + this.data.dayTpye[this.data.datStatus]).split(' '),
        endTime = this.data.addLeaveExam.endTime.split(' ');
      if ((this.data.date2 != '' && time > this.data.date2) || (startTime[0] == endTime[0] && startTime[1] == '下午' && endTime[1] == '上午')) {
        wx.showToast({
          title: '大于结束时间',
          icon: 'error'
        })
        return
      }
      this.setData({
        date1: time,
        dayStart: this.data.dayTpye[this.data.datStatus],
        [str]: this.formatDate(time) + ' ' + this.data.dayTpye[this.data.datStatus]
      })
    } else {
      var str = 'addLeaveExam.endTime',
        startTime = this.data.addLeaveExam.startTime.split(' '),
        endTime = (this.formatDate(time) + ' ' + this.data.dayTpye[this.data.datStatus]).split(' ');
      if ((this.data.date1 != '' && time < this.data.date1) || (startTime[0] == endTime[0] && startTime[1] == '下午' && endTime[1] == '上午')) {
        wx.showToast({
          title: '小于开始时间',
          icon: 'error'
        })
        return
      }
      this.setData({
        date2: time,
        dayEnd: this.data.dayTpye[this.data.datStatus],
        [str]: this.formatDate(time) + ' ' + this.data.dayTpye[this.data.datStatus]
      })
    }

    this.setData({
      showTime: false
    })
    this.calculateDays();
  },
  calculateDays() {
    var date1 = this.data.date1,
      date2 = this.data.date2,
      dayStart = this.data.dayStart,
      dayEnd = this.data.dayEnd,
      leaveTime = '';

    console.log(date1);
    console.log(dayStart);

    console.log(date2);
    console.log(dayEnd);
    if (date1 == "" && date2 == "") {
      leaveTime = '0天';
    } else if (date1 == "" || date2 == "") {
      leaveTime = '0天';
    } else if (date2 != '') {
      console.log(this.formatDate(date2));
      console.log(this.formatDate(date1));
      var days = Date.parse(this.formatDate(date2)) - Date.parse(this.formatDate(date1));
      console.log(days);
      var day = parseInt(days / (1000 * 60 * 60 * 24));
      console.log(day);
      if (date2 == date1 || (dayStart == "上午" && dayEnd == "上午") || (dayStart == "下午" && dayEnd == "下午")) {
        day = day + 0.5;
      } else if (dayStart == "上午" && dayEnd == "下午") {
        day = day + 1;
      }
      leaveTime = day + '天';
    }
    this.setData({
      leaveTime
    })
  },


  inputHandle(e) {
    console.log(e);
    var val = e.detail,
      str = e.currentTarget.dataset.str;
    this.setData({
      [str]: val
    })
    console.log(this.data);

  },

  selectCancel() {
    this.setData({
      showTime: false
    })
  },
  formatDate(date) {
    return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
  },
  // 选择上下午
  datStatusData(e) {
    console.log(e);
    var index = e.currentTarget.dataset.index
    this.setData({
      datStatus: index
    })
  },

  // 获取 详情
  resultData() {
    var examInfo = JSON.parse(wx.getStorageSync('examInfo')),
      listProps = this.data.listProps;
    listProps.readonlyStatus = true;
    this.setData({
      examInfo,
      listProps
    })
    console.log(this.data.examInfo);
    this.getExamDetail();
    if (this.data.examInfo.examMember_status == 4) {
      this.setData({
        readDataShow: true
      })
    }
    // if (wx.getStorageSync('readDataOa') != '') {
    //   this.setData({
    //     readDataShow: true
    //   })
    // }
    if (examInfo.stautsApproval != undefined) {
      this.setData({
        stautsApproval: false
      })
    }
    if (!examInfo.detial) {
      this.getPenSigner()
    }
    wx.removeStorageSync('examInfo')
    wx.removeStorageSync('readDataOa')
  },

  // 获取签名版
  getPenSigner() {
    wx.showLoading({
      title: '',
      icon: 'none'
    })
    console.log(this.data.examInfo);
    var url = app.globalData.url + 'member/getPenSigner',
      that = this;
    app.wxRequest(url, {
      memberId: app.globalData.memberId
    }, res => {
      if (res.flag) {
        if (res.data.penSigners.length == 0) {
          that.setData({
            imgApproval: ''
          })
        } else {
          that.setData({
            imgApproval: res.data.penSigners[0].penSignerImg
          })
        }
        wx.hideLoading()
      }
    })
  },
  // 获取请假详情
  getExamDetail() {
    wx.showLoading({
      title: '',
      icon: 'none'
    })
    var url = app.globalData.url + "exam/getExamDetail",
      that = this;
    app.wxRequest(url, {
      examId: that.data.examInfo.examMain_id
    }, res => {
      if (res.flag) {
        var listProps = this.data.listProps,
          strList1 = 'listProps.readonlyStatus',
          strList2 = 'listProps.topList',
          strList3 = 'listProps.btmList',
          showTime = false,
          doalig = false,
          approval_name = '',
          addLeaveExam = this.data.addLeaveExam,
          strAddLeaveExam1 = 'addLeaveExam.startTime',
          strAddLeaveExam2 = 'addLeaveExam.endTime',
          strAddLeaveExam3 = 'addLeaveExam.leaveExamHandover',
          strAddLeaveExam4 = 'addLeaveExam.leaveExamDetail',
          date1 = '',
          date2 = '',
          type = '',
          typeList = this.data.typeList,
          leaveTime = '';
        approval_name = res.data.examMain.member_name;
        addLeaveExam.startTime = res.data.leaveExam.startTime;
        addLeaveExam.endTime = res.data.leaveExam.endTime;
        addLeaveExam.leaveExamHandover = res.data.leaveExam.leaveExamHandover;
        addLeaveExam.leaveExamDetail = res.data.leaveExam.leaveExamDetail;
        date1 = res.data.leaveExam.startTime;
        date2 = res.data.leaveExam.endTime;
        type = typeList[res.data.leaveExam.leaveExamType].name;
        leaveTime = res.data.leaveExam.leaveExamDuration;
        for (var i in res.data.examMembers) {
          res.data.examMembers[i].memberName = res.data.examMembers[i].member_name;
          res.data.examMembers[i].memberImg = res.data.examMembers[i].member_img;
          if (res.data.examMembers[i].examMember_type == 0) {
            listProps.topList.push(res.data.examMembers[i])
          } else {
            listProps.btmList.push(res.data.examMembers[i])
          }
        }
        this.setData({
          [strList1]: true,
          [strList2]: listProps.topList,
          [strList3]: listProps.btmList,
          [strAddLeaveExam1]: addLeaveExam.startTime,
          [strAddLeaveExam2]: addLeaveExam.endTime,
          [strAddLeaveExam3]: addLeaveExam.leaveExamHandover,
          [strAddLeaveExam4]: addLeaveExam.leaveExamDetail,
          approval_name,
          date1,
          date2,
          type,
          leaveTime,
          showTime,
          doalig
        })
        wx.hideLoading()
      }
    })
  },

  // 获取 审批人  抄送人
  getExamProcessDetail() {
    wx.showLoading({
      title: '',
      icon: 'none'
    })
    var url = app.globalData.url + "exam/getExamProcessDetail",
      that = this,
      listProps = this.data.listProps,
      show = '';
    app.wxRequest(url, {
      examType: 0,
      memberId: app.globalData.memberId
    }, res => {
      console.log(res);
      if (res.flag) {
        listProps.topList = res.data['审批人'];
        listProps.btmList = res.data['抄送人'];
        show = true;
        console.log(listProps);
        that.setData({
          listProps,
          show
        })
        wx.hideLoading()
      }
    })
  },

  // 确认提交
  toSubmit() {
    var examMemberIdList = [],
      leaveExamTypeList = [],
      listProps = this.data.listProps,
      addLeaveExam = this.data.addLeaveExam,
      leaveTime = this.data.leaveTime;
    listProps.topList = JSON.parse(wx.getStorageSync('listProps')).topList
    for (let i in listProps.topList) {
      examMemberIdList.push(listProps.topList[i].memberId);
      leaveExamTypeList.push(0)
    }
    for (let i in listProps.btmList) {
      examMemberIdList.push(listProps.btmList[i].memberId);
      leaveExamTypeList.push(1)
    }
    if (addLeaveExam.leaveExamType.length == 0) {
      wx.showToast({
        title: '请选择请假类型',
        icon: 'none'
      })
      return
    }
    if (addLeaveExam.startTime.length == 0) {
      wx.showToast({
        title: '请假开始时间为空',
        icon: 'none'
      })
      return
    }
    if (addLeaveExam.endTime.length == 0) {
      wx.showToast({
        title: '请假结束时间为空',
        icon: 'none'
      })
      return
    }
    if (leaveTime.length == 0) {
      wx.showToast({
        title: '请假时长为空',
        icon: 'none'
      })
      return
    }
    if (addLeaveExam.leaveExamHandover.length == 0) {
      wx.showToast({
        title: '工作交接人为空',
        icon: 'none'
      })
      return
    }
    if (addLeaveExam.leaveExamDetail.length == 0) {
      wx.showToast({
        title: '请假原因',
        icon: 'none'
      })
      return
    }
    if (examMemberIdList.length == 0) {
      wx.showToast({
        title: '审批人为空',
        icon: 'none'
      })
      return
    }
    if (leaveExamTypeList.length == 0) {
      wx.showToast({
        title: '抄送为空',
        icon: 'none'
      })
      return
    }

    console.log(listProps);
    console.log(addLeaveExam);
    console.log(leaveTime);
    console.log(examMemberIdList);
    console.log(leaveExamTypeList);

    wx.showLoading({
      title: '',
      icon: 'none'
    })
    var url = app.globalData.url + "exam/addLeaveExam",
      that = this;
    app.wxRequest(url, {
      memberId: app.globalData.memberId,
      leaveExamType: addLeaveExam.leaveExamType,
      startTime: addLeaveExam.startTime,
      endTime: addLeaveExam.endTime,
      leaveExamDuration: leaveTime,
      leaveExamHandover: addLeaveExam.leaveExamHandover,
      leaveExamDetail: addLeaveExam.leaveExamDetail,
      dateTime: addLeaveExam.dateTime,
      leaveExamStatus: '0',
      examType: '0',
      note: addLeaveExam.note,
      examMemberId: examMemberIdList.toString(),
      examLeaveExamType: leaveExamTypeList.toString(),
    }, res => {
      if (res.flag) {
        wx.hideLoading()
        wx.showToast({
          title: '提交成功',
          iocn: 'none'
        })
        var obj = {
            examMain_id: res.data,
            return: true,
            detial: true,
            stautsApproval: true
          },
          listProps = {
            topList: [],
            btmList: [],
            readonlyStatus: false, // 是否只读
          };

        wx.setStorageSync('examInfo', JSON.stringify(obj))
        that.setData({
          listProps
        })
        that.resultData();
      }
    })
  },


  // 撤回
  revokeExam() {
    wx.showLoading({
      title: '',
      icon: 'none'
    })
    console.log(this.data.examInfo);
    var url = app.globalData.url + 'exam/revokeExam',
      that = this;
    app.wxRequest(url, {
      examMainId: that.data.examInfo.examMain_id
    }, res => {
      if (res.flag) {
        console.log(res);
        wx.showModal({
          title: '提示',
          content: '撤回审批成功',
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              wx.navigateBack()
              wx.removeStorageSync('examInfo')
            }
          }
        })
        wx.hideLoading()
      }
    })
  },

  // 申请销假
  addLeaveCancelExam() {
    var examMemberIdList = [],
      leaveExamTypeList = [],
      listProps = this.data.listProps,
      that = this,
      url = app.globalData.url + 'exam/addLeaveCancelExam';
    for (let i in listProps.topList) {
      examMemberIdList.push(listProps.topList[i].member_id);
      leaveExamTypeList.push(0)
    }
    for (let i in listProps.btmList) {
      examMemberIdList.push(listProps.btmList[i].member_id);
      leaveExamTypeList.push(1)
    }
    app.wxRequest(url, {
      memberId: that.data.examInfo.member_id,
      examType: 3,
      leaveExamMainId: that.data.examInfo.examMain_id,
      examMemberId: examMemberIdList.toString(),
      examLeaveExamType: leaveExamTypeList.toString(),
    }, res => {
      if (res.flag) {
        wx.showModal({
          title: '提示',
          content: '销假申请成功',
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              wx.navigateBack()
            }
          }
        })
      }
    })
  },

  // 已阅
  readData() {
    var examMemberNum = '',
      examMemberType = "",
      listProps = this.data.listProps,
      that = this,
      url = app.globalData.url + 'exam/reviewExam';
    for (let i in listProps.btmList) {
      if (listProps.btmList[i].member_id == wx.getStorageSync('member_id')) {
        examMemberNum = listProps.btmList[i].examMember_num;
        examMemberType = listProps.btmList[i].examMember_type;
      }
    }
    wx.showLoading({
      title: '',
      icon: 'none'
    })
    app.wxRequest(url, {
      examMemberId: that.data.examInfo.examMember_id,
      examMemberNum: examMemberNum,
      examMemberDetail: that.data.examInfo.examMemberDetail == undefined ? '' : that.data.examInfo.examMemberDetail,
      examMemberStatus: 1,
      examType: 0,
      examMainId: that.data.examInfo.examMain_id,
      examMemberType: examMemberType
    }, res => {
      if (res.flag) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '审核成功',
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              wx.navigateBack()
            }
          }
        })
      }
    })
  },

  // 同意 或 不同意
  approvalData(e) {
    var flag = e.currentTarget.dataset.flag;
    if (!this.data.examInfo.detial && this.data.imgApproval.length == 0) {
      wx.showModal({
        title: '提示',
        content: '暂无签名板,请完善签名板!',
        complete: (res) => {
          if (res.confirm) {
            console.log('签名版');
            wx.navigateTo({
              url: '/gerenInfo/pages/signature/signature',
            })
          }
        }
      })
      return
    }
    var examMemberNum = '',
      listProps = this.data.listProps,
      url = app.globalData.url + 'exam/reviewExam',
      that = this;
    for (let i in listProps.topList) {
      if (listProps.topList[i].member_id == wx.getStorageSync('member_id')) {
        examMemberNum = listProps.topList[i].examMember_num;
      }
    }
    wx.showLoading({
      title: '',
      icon: 'none'
    })

    app.wxRequest(url, {
      examMemberId: that.data.examInfo.examMember_id,
      examMemberNum: examMemberNum,
      examMemberDetail: that.data.examInfo.examMemberDetail == undefined ? '' : that.data.examInfo.examMemberDetail,
      examMemberStatus: flag,
      examType: that.data.examInfo.noBtn ? 0 : 3,
      note: that.data.imgApproval,
      examMainId: that.data.examInfo.examMain_id,
      examMemberType: that.data.examInfo.detial ? 1 : 0
    }, res => {
      if (res.flag) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '审核成功',
          showCancel: false,
          complete: (res) => {
            if (res.confirm) {
              wx.navigateBack()
            }
          }
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(wx.getStorageSync('readDataOa'));
    var date = new Date(),
      hour = date.getHours(),
      datStatus = '';
    if (hour > 12) {
      datStatus = 1;
    } else if (hour <= 12) {
      datStatus = 0;
    }
    this.setData({
      datStatus
    })
    if (wx.getStorageSync('examInfo') != '') {
      this.resultData()
    } else {
      this.getExamProcessDetail();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getPenSigner()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})